package com.xinting.piano.app;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.xinting.piano.R;
import com.xinting.piano.data.PUser;
import com.xinting.piano.view.PDataView;

/**
 * Created by wuxinting on 15/10/29.
 * 用户实体类的适配
 */
public class PUserAdapter {

    private Context context;
    private LayoutInflater inflater;
    private View.OnClickListener onClickListener;

    private static final int resource = R.layout.user_item;
    private static final int id = 0x7f041001;

    public PUserAdapter(Context context) {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        setOnClickListener(new OnUserClickListener());
    }

    public View getView(PUser user, LinearLayout parent) {
        if (user == null) return null;

        View view;
        view = parent.findViewById(id);
        if (view == null) {
            view = inflater.inflate(resource, parent, false);
            view.setId(id);
            parent.addView(view);
        }
        PDataView name = (PDataView) view.findViewById(R.id.nickname);
        name.setText(user.getNick());
        name.setData(user);
        if (getOnClickListener() != null) {
            name.setOnClickListener(getOnClickListener());
        }

        return view;
    }

    public View.OnClickListener getOnClickListener() {
        return onClickListener;
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    /**
     * 点击用户跳转到用户界面
     */
    private class OnUserClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view instanceof PDataView) {
                PDataView dataView = (PDataView) view;
                PUser user = (PUser) dataView.getData();
                Log.v(PUser.LOG_TAG, "Click User: " + user.getNick());

                Intent intent = new Intent();
                intent.setClass(context, PUserActivity.class);
                intent.putExtra(PUser.KEY, user);
                context.startActivity(intent);
            }
        }
    }
}
